package com.zh.yqbj.service.impl;

import cn.dev33.satoken.stp.StpInterface;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zh.yqbj.entity.Role;
import com.zh.yqbj.entity.UserRole;
import com.zh.yqbj.service.RoleService;
import com.zh.yqbj.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限加载接口实现类
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService roleService;

    @Override
    public List<String> getPermissionList(Object loginId, String s) {
        return null;
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        if (loginId == null) {
            return null;
        }
        //1. 根据用户id查询角色id
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId, loginId);
        List<UserRole> userRoles = userRoleService.list(queryWrapper);
        List<String> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        if (roleIds.isEmpty()) {
            return null;
        }
        //2. 根据角色id查询角色名
        LambdaQueryWrapper<Role> roleQueryWrapper = new LambdaQueryWrapper<>();
        // 注意原始的listByIds 不能判空，因此使用条件包
        roleQueryWrapper.in(Role::getId, roleIds);
        List<Role> roles = roleService.list(roleQueryWrapper);
        List<String> roleList = roles.stream().map(Role::getRoleName).collect(Collectors.toList());
        return roleList;
    }

}
